import { createRouter, createWebHashHistory } from "vue-router";
import { useUserStore } from "@/store/modules/useUserStore.js";
import { routes } from "./routes";
import { ElMessage } from "element-plus";

const router = createRouter({
  history: createWebHashHistory(),
  routes
});

const whiteList = ["/Login"];

router.beforeEach((to, from, next) => {
  //必须在拦截器里初始化store
  const { userToken, userInfo } = useUserStore().getLocalUserInfo() || {};
  const { user_role } = userInfo || {};

  // 拦截不在白名单的路由
  if (whiteList.indexOf(to.path) !== -1) {
    next();
    return;
  }

  if (userToken && user_role === "admin") {
    // 存在token，且是要进入login页面，则让其跳转到首页
    if (to.path === "/Login") {
      next({ path: "/Home" });
    } else {
      // 不为空则正常跳转
      next();
    }
  } else {
    if (user_role === "admin") {
      ElMessage.error("请先登录!");
    } else {
      ElMessage.error("您没有权限访问此页面!");
    }
    next("/Login");
  }
});

router.afterEach((to, from) => {
  document.title = to.meta.title || "Himate后台管理系统"; //修改网页的title
});
export default router;
